/* 
 * Mashup Javascript w/ JQuery
 * Author: Fei Hu
 */

var url;
var marker_counter = 0; // marker counter
var marker_array = new Array();
//$(document).ready(function(){

window.onload = loadScript;
// google.maps.event.addDomListener(window, 'load', initialize);

function loadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.google.com/maps/api/js?sensor=true&callback=initialize";
  document.body.appendChild(script);
}



function ajaxSearch(){
    $.ajax({
        type: 'POST',
        url: 'twitter.php',
        data: ({
            keywords : $('#keywords').val()
        }),
        dataType: 'json',
        beforeSend: function(){$('#loadingimg').html('<img src="ajax-loader.gif">');},
        success: serverResponse,
        error: function(){
            alert('Error during AJAX call. Please try again');
        },
        ajaxStop: function(){loading(0);}

    });
}

/*
 * Integration GOOGLE MAP API
 */
var geocoder;
var map;

/*
 * Initialize google map when loading page
 */
function initialize() {
    // Enable HTML 5 Geolcation
    if(navigator.geolocation) {
        function hasPosition(position) {
            var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            myOptions = {
                zoom: 8,
                center: point,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById("map_canvas"),
                myOptions);

        //            marker = new google.maps.Marker({
        //                position: point,
        //                map: map,
        //                title: "You are here"
        //            });
        }
        
        navigator.geolocation.getCurrentPosition(hasPosition);

    } else { // if browser doesn't support HTML5 geolocation, use the default location
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
    }
}

function serverResponse(data){
    // remove loading image
    $('#loadingimg').html('');
    
    var twitterList = $('#twitterList');
    twitterList.html(""); //empty content

	marker_array.length = 0; // empty marker array or array.empty()
	// marker_array = [];
	// for(var key in data) {
	for(i=0; i < data.length; i++) {	
        var user = data[i].name;
        var create_time = data[i].time;
        var imageUrl = data[i].img;
        var content = data[i].text;
        var location = data[i].loc;

        // add Marker on GOOGLE MAP
        //       markAddress(location, user);
        //        alert(user);
        //        var li = tmpl.cloneNode(true);
        //        $(li).find('a').attr('href',userUri)
        //        .end().find('img').attr('src',imageUrl).attr('alt',user)
        //        .end().find('span a').text(user)
        //        .end().find('p').text(content);
      
        var li = $("<li></li>")
        .append(
            "<a href='#'>" +
            "<img alt='"+user+"' src='" + imageUrl + "' />" +
            "</a>")
        .append(
            "<span>" + "<a href='#'>" + user + "</a>"+":"+content+"</span>")
        // .append(content + "</span>")
        .click(function(){
			if(document.getElementById(this.id)){
			map.panTo(marker_array[this.id].getPosition()); //pan to user location
			// alert(this.id);
			}
         });
		
		if(location !== null && location !== "null" && location !=="") {
				li.attr("id",marker_counter);				
		        var userInfo = [content,imageUrl,marker_counter];
		        markAddress(location,userInfo);				
				marker_counter++;				
			}		
        twitterList.append(li);
	}
// draw markers on google map
	marker_counter = 0;
}


/*
 * add Marker on GOOGLE MAP
 * may add the marker later by calling the marker's setMap() method.
 * pass null as the argument if remove a marker
 *
 * Accessing the Geocoding service is asynchronous, since the Google Maps API
 * needs to make a call to an external server. For that reason, you need to
 * pass a callback method to execute upon completion of the request.
 * This callback method processes the result(s). Note that the geocoder may
 * return more than one result.
 * You access the Google Maps API geocoding service within your code via the
 * google.maps.Geocoder object. The Geocoder.geocode() method initiates
 * a request to the geocoding service, passing it a GeocodeRequest object
 * literal containing the input terms and a callback method to execute upon
 * receipt of the response.
 */
function markAddress(location,userInfo) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( {
        'address': location
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var contentString = '<div id="infowin">'+'<em>'+userInfo[0]+'</em></div>';
            var infowindow = new google.maps.InfoWindow({
                content: contentString,
                maxWidth: 100
            });
			var image = unescape(userInfo[1]); // decode!
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                animation: google.maps.Animation.DROP,
				icon: image,
                title: "Marker"+userInfo[2]
            });
			
			marker_array.push(marker);
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.open(map,marker);
            });

        } else {
//            alert("Geocode was not successful for the following reason: " + status);
        }
    });
       
}
// End of integration GOOGLE MAP API

/*
 * Click function: pan to the mark when click tweet
 */
function centerMarker(id){
    alert("centerMarker->"+marker.getTitle());
    map.panTo(marker.getPosition());
}
// End of click function
